package com.lmx.web.controller.thirdPart;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lmx.persistence.service.HealthInfoService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/*-
 * 处理接口
 */

@Controller
@RequestMapping("/access/guihua")
public class GuiHuaController {
	private static Log logger = LogFactory.getLog(GuiHuaController.class);

	@Autowired
	private HealthInfoService healthInfoService;

	// 收取推送的设备信息
	@RequestMapping("/receiveDeviceData")
	@ResponseBody
	public void receiveDeviceData(HttpServletRequest request, HttpServletResponse response) {
		logger.debug("---------------start receive guihua data-------------------------------------");
		BufferedReader in = null;
		String result = "";
		try {
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(request.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			//{\"type\":\"BP\",\"value\":\"130:90:67\",\"mac\":\"18:7A:93:02:98:C4\",\"timestamp\":1504596720,\"hub_mac\":\"CC:1B:E0:E0:0A:28\"}
            // result="{\"type\":\"Glucose\",\"value\":98,\"mac\":\"C0:26:DF:00:E6:2B\",\"timestamp\":1504597183,\"hub_mac\":\"CC:1B:E0:E0:0A:28\"}";
			logger.debug("receive guihua data " + result);
			if (result != null && !"".equals(result)) {
				if(result.startsWith("[")&&result.endsWith("]")){
					
				}else{
					result="["+result+"]";
				}
				JSONArray jsonArray = JSONArray.fromObject(result);
				for (int i = 0; i < jsonArray.size(); i++) {
					JSONObject object = jsonArray.getJSONObject(i);
					if (object.containsKey("type")) {
						healthInfoService.createGuiHuaHealthinfo(object);
					}
				}
			}
			logger.debug("receive guihua data: " + result);
			BufferedOutputStream out;
			out = new BufferedOutputStream(response.getOutputStream());
			out.write("receive guihua data ok".getBytes());
			out.flush();
			out.close();
		} catch (Exception e) {
			logger.debug("receive guihua data Exception: " + e.toString());
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				logger.debug("receive guihua data error " + ex);
			}
		}
		logger.debug("---------------end receive guihua data-------------------------------------");// 数据处理
	}

}
